//
//  NYSquareView.m
//  BS
//
//  Created by neal on 15/8/19.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NYSquareView.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import "NYSquareModel.h"
#import "NYSquareButton.h"
@interface NYSquareView ()
/* 模型 */
@property (nonatomic,strong)  NSArray *square_list;

@end
@implementation NYSquareView

- (instancetype)initWithFrame:(CGRect)frame
{
    if ( self = [super initWithFrame:frame]) {
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"a"] = @"square";
        parameters[@"c"] = @"topic";
        
        [[AFHTTPSessionManager manager] GET:NYBaseURL parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
            self.square_list = [NYSquareModel objectArrayWithKeyValuesArray:responseObject[@"square_list"]];
            [self setsquareButton];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NYLog(@"网络不给力");
        }];
    }
    return self;
}
- (void)setsquareButton
{
    NSUInteger count = self.square_list.count;
    int totalColCount = 4;
    CGFloat buttonW = NYScreenW / totalColCount;
    CGFloat buttonH = buttonW ;

    for (int i = 0; i < count; i++) {
        NYSquareButton *button = [NYSquareButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:button];
        
        CGFloat buttonX = (i % totalColCount) * buttonW;
        CGFloat buttonY = (i / totalColCount) * buttonH;
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        button.square = self.square_list[i];

        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        self.height = CGRectGetMaxY(button.frame);
    }
    //重新计算底部的frame，解决3.5等尺寸是无法滑到底部
    UITableView *tableview = (UITableView *)self.superview;
    tableview.contentSize = CGSizeMake(tableview.contentSize.width, CGRectGetMaxY(self.frame));
}
- (void)buttonClick:(NYSquareButton *)button
{
    NSLog(@"%@",button.square.name);
}
@end
